<?php
require_once("dao/MailDao.php");
if ($_SESSION['niveauAuth']<>'0'){
function liste_fichiers($dir, $client) 
{ 
	//faire la recherche sur le code client
	$code_client = $client;
	
	//scan le repertoire
	$root = scandir($dir); 
	foreach($root as $value) 
	{ 
		if($value === '.' || $value === '..') {continue;} 
		if(is_file("$dir/$value")) {$result[]="$dir/$value";continue;} 
		foreach(liste_fichiers("$dir/$value",$code_client) as $value) 
		{ 
			//vérifie si des factures existent pour le client
			if(preg_match('/'.'-'.$code_client.'-'.'/', '/'.$value.'/'))  
				{
					echo $value."<br>";
				$result[]=$value;
				}
		} 
	} 
	return $result; 
} 

//$requete = $bdd->prepare(" SELECT * FROM fiche_client WHERE code_client_hto = '2022011'");
$requete = $bdd->prepare(" SELECT * FROM fiche_client ");
$requete->execute();
$infoclient=$requete->fetchall(PDO::FETCH_ASSOC);
$requete->closeCursor();

$errorsMails = 0;
$sentMails = 0;
//traitement client par client	
foreach($infoclient as $cle => $donneesclients)
{	
	//copie des factures temporaires
	////////////////////////////////////////
	if($donneesclients['code_client_hto'])
	{
		$tab_factures = liste_fichiers("facture_temp",$donneesclients['code_client_hto']);
		$tab_factures_encours=array();
		foreach($tab_factures as $cle => $facture)
		{
			if(substr(str_replace("facture_temp/","",$facture),0,6)==date("mY")) 
			{ 
				copy($facture, str_replace("facture_temp/","facture/",$facture));
				$tab_factures_encours[] = $facture;
			}
		}
		
		//vérifie si le détail existe
		if(glob("facture_temp/csv/".date("mY")."/".$donneesclients['code_client_hto']."_".date("mY")."_regroup.csv"))
		{
			$detail_facture = "facture_temp/csv/".date("mY")."/".$donneesclients['code_client_hto']."_".date("mY")."_regroup.csv";
			copy($detail_facture, str_replace("facture_temp/","facture/",$detail_facture));
			$tab_factures_encours[] = $detail_facture;
		}
	}
	//if(substr(str_replace("facture/","",)),0,6))==date("mY")){echo 'ok';}
	//echo $donneesclients['code_client_hto'];
	
	//var_dump($tab_factures_encours);
	
	if(MailDao::EnvoiMailFacture($donneesclients['email'],$tab_factures_encours)){ 

            //suppression des factures temporaires
            foreach($tab_factures_encours as $cle => $facture)
            {
                unlink($facture);
            }

            $req = $bdd->prepare(" UPDATE admin_facture SET facture = REPLACE(facture, 'facture_temp/', 'facture/') WHERE id_client = ".$donneesclients['id']." ");
            $req->execute();
            $sentMails++;
        }else{
            $errorsMails++;
        }
}
if($sentMails>0){
    $sentMessage = array('message' => "$sentMails mails envoyés", 'type' => 'success');
    $_SESSION['alerts'][] = $sentMessage;
}elseif($errorsMails==0){
    $sentMessage = array('message' => "Aucun mail à envoyer", 'type' => 'warning');
    $_SESSION['alerts'][] = $sentMessage;
}
if($errorsMails>0){
    $errorMessage = array('message' => "$errorsMails mails en erreurs ! Contactez l'administrateur", 'type' => 'error');
    $_SESSION['alerts'][] = $errorMessage;
}



redirect("lancement-facture");

}
else {
	redirect("home-admin");
}

 
